//
//  CompanyCertV2ViewModel.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/9.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "CompanyCertV2ViewModel.h"

@interface CompanyCertV2ViewModel ()

@property (nonatomic, copy) NSString* strContactZone;

@end

@implementation CompanyCertV2ViewModel

#pragma mark - Ovrride
- (void)initialize
{
    [super initialize];
    
    @weakify(self)
    
    _isReload = NO;
    
    _stepIndex = 0;
    
    _busyCertImages = [NSMutableArray array];
    
    [[RACObserve(self, isInPreview) filter:^BOOL(id value) {
        
        BOOL result = [value boolValue];
        
        return result;
    }] subscribeNext:^(id x)
     {
         @strongify(self);
         
         self.waitDelIndexes = [NSMutableArray array];
     }];
    
    DataManager* dm = [DataManager sharedDataManager];
    self.zoneData = dm.locationPLData;
    
    RACSignal* zoneChangeSignal = [RACObserve(self, zoneData) distinctUntilChanged];
    [[zoneChangeSignal replay] subscribeNext:^(id x)
     {
         @strongify(self);
         
         ProvinceListData* curPListData = x;
         
         if (x == nil)
         {
             self.strContactZone = @"选择城市 >";
         }
         else
         {
             self.strContactZone = HCStrFormat(@"%@ >", curPListData.name);
         }
     }];
    
    self.reloadCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        
        @strongify(self);
        
        @weakify(self);
        return [[self _requestReloadSignal] doNext:^(id x)
                {
                    @strongify(self);
                    
                    [self _reload:x];
                }];
    }];
    
    self.addImgCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        
        @strongify(self);
        
        NSMutableArray* opUIImageDatas = [NSMutableArray array];
        for (UIImage* curImg in input)
        {
            EPUIImageData* epUIImageData = [EPUIImageData createWithImage:curImg imgData:nil];
            [opUIImageDatas addObject:epUIImageData];
        }
        
        NSMutableArray* newUploadImgs = [NSMutableArray arrayWithArray:[self.busyCertImages arrayByAddingObjectsFromArray:opUIImageDatas]];
        self.busyCertImages = newUploadImgs;
        
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
            
            return nil;
        }];
    }];
    
    self.deleteImgCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        
        @strongify(self);
        
        NSInteger delIndex = [input integerValue];
        
        EPUIImageData* delImgData = self.busyCertImages[delIndex];
        
        [self.busyCertImages removeObjectAtIndex:delIndex];
        self.busyCertImages = [NSMutableArray arrayWithArray:self.busyCertImages];
        
        if (delImgData.imgData)
        {
            return [self requestDelImgSignal:delImgData.imgData];
        }
        else
        {
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                
                [subscriber sendNext:nil];
                [subscriber sendCompleted];
                
                return nil;
            }];
        }
    }];
    
    self.deleteImgsCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        
        @strongify(self);
        
        NSMutableArray* delImgs = [NSMutableArray array];
        
        for (NSNumber* delIndexNum in self.waitDelIndexes)
        {
            NSInteger delIndex = [delIndexNum integerValue];
            
            [delImgs addObject:self.busyCertImages[delIndex]];
        }
        
        [self.busyCertImages removeObjectsInArray:delImgs];
        NSMutableArray* newImgs = [NSMutableArray arrayWithArray:self.busyCertImages];
        self.busyCertImages = newImgs;
        
        RACSignal* reqSignal = nil;
        
        for (NSInteger index=0; index<delImgs.count; index++)
        {
            EPUIImageData* uiimgData = delImgs[index];
            
            RACSignal* delImgSignal = [self requestDelImgSignal:uiimgData.imgData];
            
            if (reqSignal == nil)
            {
                reqSignal = delImgSignal;
            }
            else
            {
                reqSignal = [reqSignal then:^RACSignal *{
                    return delImgSignal;
                }];
            }
        }
        
        if (reqSignal)
            return reqSignal;
        
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
            
            return nil;
        }];
    }];
    
    self.submitCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
                      {
                          @strongify(self);
                          
                          if (!self.strCompanyName || ![self.strCompanyName isNotBlank])
                          {
                              return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:@"请填写公司名"}]];
                          }
                          
                          if (!self.strContactName || ![self.strContactName isNotBlank])
                          {
                              return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:@"请填写联系人"}]];
                          }
                          
                          if (!self.strContactPhone || ![self.strContactPhone isNotBlank])
                          {
                              return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:@"请填写联系手机"}]];
                          }
                          
                          if (!self.strContactAddr || ![self.strContactAddr isNotBlank])
                          {
                              return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:@"请填写联系地址"}]];
                          }
                          
                          if (self.busyCertImages.count == 0)
                          {
                              return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:@"请上传营业执照"}]];
                          }
                          
                          RACSignal* reqSignal = nil;
                          
                          for (NSInteger index=0; index<self.busyCertImages.count; index++)
                          {
                              EPUIImageData* busyCertImage = self.busyCertImages[index];
                              
                              if (busyCertImage.imgData!=nil)
                              {
                                  continue;
                              }
                              
                              RACSignal* uploadImgSignal = [[self requestUplaodImg:busyCertImage.img] delay:1.0f];
                              
                              if (reqSignal == nil)
                              {
                                  reqSignal = uploadImgSignal;
                              }
                              else
                              {
                                  reqSignal = [reqSignal then:^RACSignal *{
                                      return uploadImgSignal;
                                  }];
                              }
                          }
                          
                          if (reqSignal==nil)
                          {
                              return [self requestSubmitSignal];
                          }
                          
                          @weakify(self);
                          return [reqSignal then:^RACSignal *{
                              @strongify(self);
                              return [self requestSubmitSignal];
                          }];
                      }];
}

- (void)_reload:(EnterpriseDetailInfoData*)detailInfoData
{
    @weakify(self);
    
    DataManager* dm = [DataManager sharedDataManager];
    
    NSMutableArray* epimgDatas = [NSMutableArray arrayWithArray:detailInfoData.enterpriseImage];
    
    self.zoneData = [dm findCityDataBy:detailInfoData.enterpriseInfo.areaID];
    
    self.strCompanyName = detailInfoData.enterpriseInfo.name;
    self.strCompanyIntro = detailInfoData.enterpriseInfo.summary;
    self.strContactName = detailInfoData.enterpriseInfo.contacts;
    self.strContactPhone = detailInfoData.enterpriseInfo.mobile;
    self.strContactAddr = detailInfoData.enterpriseInfo.address;
    
    NSMutableArray* keepBusyCertImgs = [NSMutableArray array];
    NSMutableArray* busyCertEpImgDatas = [NSMutableArray array];
    
    for (NSInteger index=0; index<epimgDatas.count; index++)
    {
        EPImageData* curEPImgData = epimgDatas[index];
        NSInteger type = [curEPImgData.type integerValue];
        
        [busyCertEpImgDatas addObject:curEPImgData];
    }
    
    [self _loadMoreImage:busyCertEpImgDatas keepImgs:keepBusyCertImgs allFinish:^
     {
         @strongify(self);
         
         self.busyCertImages = keepBusyCertImgs;
     }];
}

- (void)_loadMoreImage:(NSMutableArray*)imgDatas keepImgs:(NSMutableArray*)keepImgs allFinish:(VoidBlock)allFinish
{
    @weakify(self);
    
    if (imgDatas.count > 0)
    {
        EPImageData* imgData = imgDatas[0];
        
        [self _loadImage:imgData finish:^(UIImage* image)
         {
             @strongify(self);
             
             if (image)
             {
                 EPUIImageData* uiimageData = [EPUIImageData createWithImage:image imgData:imgData];
                 
                 [keepImgs addObject:uiimageData];
             }
             else
             {
                 NSLog(@"image为nil");
             }
             
             [imgDatas removeObjectAtIndex:0];
             
             [self _loadMoreImage:imgDatas keepImgs:keepImgs allFinish:allFinish];
         }];
    }
    else
    {
        allFinish();
    }
}

- (void)_loadImage:(EPImageData*)epImgData finish:(VoidBlock_id)finishBlock
{
    @weakify(self);
    
    UIImageView* imgview = [[UIImageView alloc] initWithFrame:(CGRect) {-10000, -10000, 100, 100}];
    [imgview yy_setImageWithURL:[NSURL URLWithString:epImgData.imageurl] placeholder:MHImageNamed(@"placeholderLogo") options:YYWebImageOptionIgnorePlaceHolder completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error)
     {
         @strongify(self);
         
         YYWebImageManager* manager = [YYWebImageManager sharedManager];
         NSString* key = [manager cacheKeyForURL:url];
         UIImage* curImg = [manager.cache getImageForKey:key];
         
         [imgview removeFromSuperview];
         
         finishBlock(curImg);
     }];
    [[UIViewController getCurrentVC].view addSubview:imgview];
}

#pragma mark - Signal
- (RACSignal*)_requestReloadSignal
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    NSString* strUserID = um.userData.userID;
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                [[AFNetWorkUtils racPOSTWthURL:url_interface_enterpriseInfo params:interface_param_enterpriseInfo(strUserID)] subscribeNext:^(id x)
                 {
                     EnterpriseDetailInfoData* enterpriseDetailInfoData = [EnterpriseDetailInfoData modelWithJSON:x];
                     
                     [subscriber sendNext:enterpriseDetailInfoData];
                     [subscriber sendCompleted];
                 } error:^(NSError *error)
                 {
                     NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"获取审核资料失败";
                     [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

- (RACSignal*)requestDelImgSignal:(EPImageData*)imageData
{
    @weakify(self);
    
    NSString* strImgID = imageData.imageID;
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                [[AFNetWorkUtils racPOSTWthURL:url_interface_enterprise_deleteexamineimage params:interface_param_enterprise_deleteexamineimage(strImgID)] subscribeNext:^(id x)
                 {
                     [subscriber sendNext:@YES];
                     [subscriber sendCompleted];
                 } error:^(NSError *error)
                 {
                     NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"上传图片失败";
                     [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

- (RACSignal*)requestUplaodImg:(UIImage*)image
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    NSString* strUserID = um.userData.userID;
    
    CGSize uImgSize = image.size;
    UIImage* newUploadImg = [image hyb_clipToSize:(CGSize){100, 100*uImgSize.height/uImgSize.width} isEqualScale:YES];
    NSString* strImage = [UIImagePNGRepresentation(newUploadImg) base64EncodedStringWithOptions:0];
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                [[AFNetWorkUtils racPOSTWthURL:url_interface_enterprise_uploadexamineimage params:interface_param_enterprise_uploadexamineimage(strUserID, strImage)] subscribeNext:^(id x)
                 {
                     [subscriber sendNext:[EPImageData modelWithJSON:x]];
                     [subscriber sendCompleted];
                 } error:^(NSError *error)
                 {
                     NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"上传图片失败";
                     [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

- (RACSignal*)requestSubmitSignal
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    NSString* strUserID = um.userData.userID;
    NSString* strEnterpriseID = um.userDetailData.content.enterpriseID;
    
    NSString* areaID = HCStrValid(self.zoneData.areaID);
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                @strongify(self);
                
                NSString* reqUrl = self.isReload ? url_interface_enterprise_summaryedit : url_interface_enterprise_submitexamine;
                NSDictionary* postData = self.isReload ? interface_param_enterprise_summaryedit(strEnterpriseID, self.strContactPhone, self.strContactName, self.strCompanyName, areaID, self.strContactAddr, self.strCompanyIntro, @"1") : interface_param_enterprise_submitexamine(strUserID, self.strContactPhone, self.strContactName, self.strCompanyName, areaID, self.strContactAddr, self.strCompanyIntro);
                
                [[AFNetWorkUtils racPOSTWthURL:reqUrl params:postData] subscribeNext:^(id x)
                 {
                     [subscriber sendNext:x[SUCommandSysMessageKey]];
                     [subscriber sendCompleted];
                 } error:^(NSError *error)
                 {
                     NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"提交企业审核失败";
                     [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

@end
